package org.elanfox.intellicommunity.msg.server.mq;

import org.apache.http.MethodNotSupportedException;
import org.elanfox.intellicommunity.common.constant.RedisConstant;
import org.elanfox.intellicommunity.msg.constant.MsgConstant;
import org.elanfox.intellicommunity.msg.dto.CmdDTO;
import org.elanfox.intellicommunity.msg.ienum.CmdEnums;
import org.elanfox.intellicommunity.msg.server.base.WriteResult;
import org.elanfox.intellicommunity.msg.server.service.CmdWriterBuilder;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author allan
 * @version 1.0.0
 * @date 2019/12/12
 */
@Component
public class MsgConsumer {
    @Autowired
    private CmdWriterBuilder writerBuilder;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 接受指令消息
     *
     * @param msg
     */
    @RabbitListener(queues = MsgConstant.QUEUE_COMMAND_REQ)
    public void cmdProcess(Map<String, Object> msg) throws MethodNotSupportedException {
        CmdDTO cmdDTO = (CmdDTO) msg.get("msg");
        //发送到设备
        WriteResult writeResult = writerBuilder.builder(cmdDTO.getCmdCode()).write(cmdDTO.getCmdCode(), cmdDTO.getCmdWriteParam());

        if (!writeResult.isSuccess()) {
            //失败了直接修改redis中的状态
            cmdDTO.getCmdStatus().setStatus(CmdEnums.Status.FAILED);
            redisTemplate.opsForHash().put(
                    RedisConstant.KEY_CMD + cmdDTO.getHexAddr(),
                    CmdEnums.Code.LF_SCOPE.getCode(),
                    cmdDTO
            );
        }
    }
}
